<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-28
 * Time: 17:53
 */

namespace app\api\service\goods;


use app\api\model\GoodsOrder;
use app\api\model\GoodsOrderContent;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;

class CreateOrder extends Token
{
    /**
     * 1.判断购物车信息
     * 2.判断地址信息
     * 3.创建订单信息
     */
    // 用户信息
    private $user;

    // 前端传来的信息
    private $postArr;

    // 购物车信息
    private $goodsOrderContent;

    // 订单价格
    private $price;

    function __construct($postArr)
    {
        $this->user = User::get(self::getCurrentUid());
        $this->postArr = $postArr;
        $this->postArr['goods_ids'] = explode("-",$this->postArr['goods_ids']);
        $this->goodsOrderContent = GoodsOrderContent::where('goods_id','in',$this->postArr['goods_ids'])
            ->where('order_id','eq',0)
            ->where('user_id','eq',$this->user['id'])
            ->select();
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeData();
    }

    // 判断购物车信息
    private function judgeData()
    {
        if($this->goodsOrderContent->isEmpty()) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '结算商品为空'
                ]
            ]);
        }
        $this->goodsOrderContent = $this->goodsOrderContent->toArray();
        $this->price = 0;
        foreach ($this->goodsOrderContent as $k=>$v) {
            $this->price += round($this->goodsOrderContent[$k]['price']*$this->goodsOrderContent[$k]['number'],2);
        }
        return $this->createOrder();
    }

    // 创建订单信息
    private function createOrder()
    {
        // 创建订单
        Db::startTrans();
        try{
            $mode = GoodsOrder::create([
                'user_id' => $this->user['id'],
                'price' => $this->price,
                'order_no' => self::makeOrderNo(),
            ]);
            $out_trade_no = '3zheng2020'.$mode->id;
            $mode->out_trade_no = $out_trade_no;
            $mode->save();
            GoodsOrderContent::where('goods_id','in',$this->postArr['goods_ids'])
                ->where('order_id','eq',0)
                ->where('user_id','eq',$this->user['id'])
                ->update([
                    'order_id' => $mode->id
                ]);
            Db::commit();
            return writeJson(201, [ 'out_trade_no'=>$out_trade_no ], '订单生成成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}